package liuyang.bigeventserver.modules.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import liuyang.bigeventserver.common.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 配合UsernamePasswordAuthenticationFilter使用
 * 也可以给默认登录页面用
 *
 * @author liuyang
 * @since 2022/1/25
 *        2024/2/27 更换为jakarta包，并组件化@Component
 */
@Component
@Slf4j
@AllArgsConstructor
public class RespJsonAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper om;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //ObjectMapper om = new ObjectMapper();

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        //response.setStatus(HttpStatus.UNAUTHORIZED.value());// 如果返回这个，前端axios会跑到error处理流程，而不再解析返回的请求体
        response.setStatus(HttpStatus.OK.value());// 202403081555 临时修改。 除登录外其他时候的未授权处理返回状态为401，见RespJsonAuthenticationEntryPoint。 这个策略只是临时配合前端。
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        response.getWriter().println(om.writeValueAsString(R.error("认证失败").put("data", exception.getMessage())));

        log.error(exception.getMessage(), exception);
    }
}
